import 'default-passive-events';
import { AssetManager, assetManager, Label, Node, Sprite, SpriteFrame, _decorator } from 'cc';
import { core, Mediator } from 'cfw';
import { LoadingLogo } from './loading-logo';
import { USE_OVERSEA, isCN } from './env';

const { ccclass, property } = _decorator;

@ccclass('cocosmos.preload-mediator')
export class PreloadMediator extends Mediator {

    @property(Node) public btnEnter: Node = null;
    @property(Label) public tipLabel: Label = null;
    @property(LoadingLogo) public logo: LoadingLogo = null;
    @property(Node) public ipc: Node = null;
    @property(Node) public aws: Node = null;
    @property(Node) public cocos: Node = null;
    @property(Node) public updates: Node = null;

    @property(SpriteFrame) public startCN: SpriteFrame = null;
    @property(SpriteFrame) public startEN: SpriteFrame = null;

    protected onLoad(): void {
        this.btnEnter.active = false;
        this.ipc.active = this.updates.active = !USE_OVERSEA;
        this.ipc.active = false; // temp add
        this.aws.active = this.cocos.active = USE_OVERSEA;
    }

    protected async start(): Promise<void> {
        const cn = isCN();
        this.btnEnter.getComponent(Sprite).spriteFrame = cn ? this.startCN : this.startEN;
        this.tipLabel.string = cn ? `宇宙加载中0%……` : 'Cosmic Loading 0%...';
        this._preloadScene();
    }

    private _preloadScene(): void {
        const cn = isCN();
        assetManager.loadBundle(MAIN_BUNDLE, (err, bundle: AssetManager.Bundle) => {
            if (err) console.error("[scene load failed]", MAIN_BUNDLE);
            else {
                bundle.loadScene(MAIN_SCENE, (finished: number, total: number, item?: AssetManager.RequestItem) => {
                    const progress = (finished / total);
                    if (progress >= this._curr) {
                        const p = (progress * 100).toFixed(1);
                        this.tipLabel.string = cn ? `宇宙加载中${p}%……` : `Cosmic Loading ${p}%...`;
                        this.logo.setProgress(progress);
                        this._curr = progress;
                    }
                }, err => {
                    if (err) console.error("[scene load failed]", MAIN_SCENE);
                    else {
                        this.btnEnter.active = true;
                        this.tipLabel.node.active = false;
                    }
                });
            }
        });
    }

    protected clickEnter(): void {
        this.btnEnter.active = false;
        this.tipLabel.node.active = true;
        this.tipLabel.string = isCN() ? "正在进入宇宙……" : 'Entering the Cosmos...';
        this.scheduleOnce(() => core.scene.goto(MAIN_SCENE));
    }

    private _curr: num.pct = 0;
}

const MAIN_BUNDLE = 'cosmos';
const MAIN_SCENE = 'cosmos';